package space.edge.d.demo.qrcode.codescanner.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

import space.edge.d.demo.qrcode.R;

/**
 * Created by gsl on 2017/11/8.
 * previewLayout
 */

public class PreviewLayout extends FrameLayout {

    private View child;
    private int screenW, screenH;
    private Paint paint;
    private Rect rect;

    public PreviewLayout(@NonNull Context context) {
        super(context);
        init(context);
    }

    public PreviewLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PreviewLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.layout_preview, this, true);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display dm;
        if (wm != null) {
            dm = wm.getDefaultDisplay();
            Point point = new Point();
            dm.getSize(point);
            screenW = point.x;
            screenH = point.y;
        }
        paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStyle(Paint.Style.STROKE);
        rect = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        child = findViewById(R.id.v_preview);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int wSpec = MeasureSpec.makeMeasureSpec(screenW, MeasureSpec.EXACTLY);
        int hSpec = MeasureSpec.makeMeasureSpec(screenH, MeasureSpec.EXACTLY);
        child.measure(wSpec, hSpec);
        int sizeW = MeasureSpec.getSize(widthMeasureSpec);
        int sizeH = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(sizeW, sizeH);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int cW = child.getMeasuredWidth();
        int cH = child.getMeasuredHeight();
        int pW = getMeasuredWidth();
        int pH = getMeasuredHeight();
        int childLeft = (pW - cW) / 2;
        int childTop = (pH - cH) / 2;
        child.layout(childLeft, childTop, childLeft + cW, childTop + cH);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
}
